import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { permissionSessionKeyName } from '@/config/permissionMap'
import {
  getSession,
  savePermissionData,
  setPermissionRouter,
  getCurrentSessionData,
} from '@/utils/permission'
import { UserModule } from '@/store/modules/user'
import { throwErrorMessage } from '@/mixins/DefaultMixin'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async (to: { meta: { title: any } }, from: any, next: () => void) => {
  // 打开顶部进度条
  NProgress.start()
  // 设置页面title
  document.title = getPageTitle((to.meta && to.meta.title) || '')

  // 用户信息设置
  if (!UserModule.userInfo || Object.keys(UserModule.userInfo).length === 0) {
    // 无用户信息 等待获取
    const _res: any = await UserModule.GetUserInfo()
    if (!_res) {
      throwErrorMessage()
    }
  }

  // 权限验证
  const _sessionData = getSession(permissionSessionKeyName)
  if (!_sessionData) {
    // 不存在权限数据缓存
    // 请求接口
    const _res: any = await UserModule.GetUserPermission()
    if (_res && _res.data) {
      // 存储数据
      savePermissionData(_res.data)
      // // 处理路由
      setPermissionRouter(_res.data.routerPermission, _res.data.permissionList)
    } else {
      throwErrorMessage()
      next()
    }
  } else {
    let _sessionData = null
    // 初始化 - 操作权限
    if (!UserModule.buttonPermission || UserModule.buttonPermission.length === 0) {
      _sessionData = getCurrentSessionData(permissionSessionKeyName) || {}
      UserModule.SetButtonPermission(_sessionData.buttonPermission || [])
    }
    // 初始化 - 路由权限
    if (!UserModule.routerPermission || UserModule.routerPermission.length === 0) {
      if (!_sessionData) {
        _sessionData = getCurrentSessionData(permissionSessionKeyName) || {}
      }
      UserModule.SetRouterPermission(_sessionData.routerPermission || [])
    }
    // 初始化 - 总权限
    if (!UserModule.permissionList || Object.keys(UserModule.permissionList).length === 0) {
      if (!_sessionData) {
        _sessionData = getCurrentSessionData(permissionSessionKeyName) || {}
      }
      UserModule.SetPermissionList(_sessionData.permissionList || {})
    }
    next()
  }
})

router.afterEach(() => {
  // 结束顶部进度条
  NProgress.done()
})
